package cn.edu.nuc.creditSystem.controller.credit;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;

import cn.edu.nuc.creditSystem.bean.credit.Authentication;
import cn.edu.nuc.creditSystem.bean.user.User;
import cn.edu.nuc.creditSystem.controller.BaseController;
import cn.edu.nuc.creditSystem.service.BaseService;
import cn.edu.nuc.creditSystem.service.credit.service.AuthenticationService;

@Controller
@RequestMapping("/cs/credit")
public class AuthenticationController extends BaseController<Authentication>{
	@Autowired
	private AuthenticationService as;
	@Override
	protected BaseService<Authentication> getService() {
		return as;
	}

	@Override
	protected String getPrefix() {
		return "/credit";
	}
	@RequestMapping("/apply")
	private String  AuthenticationApply(){
		return "/credit/apply";
	}
	@RequestMapping("/applyInf")
	@ResponseBody
	private Authentication applyInf(HttpSession session){
		User user=(User) session.getAttribute("user");
		return as.getByUserId(user.getId())==null?new Authentication():as.getByUserId(user.getId());
	}
	@RequestMapping("/saveAuthentication")
	@ResponseBody
	private String saveAuthentication(HttpSession session,Authentication param,MultipartFile file,HttpServletRequest request,Model model){
		File f=new File(request.getSession().getServletContext().getRealPath("/authentication"));
		String fileName=UUID.randomUUID().toString()+"."+file.getName().substring(file.getName().lastIndexOf(".")+1);
		User user=(User) session.getAttribute("user");
		param.setMaterialurl("/authentication/"+fileName);
		param.setUserid(user.getId());
		try {
			if(!file.isEmpty())
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(f,fileName));
			Gson gson =new Gson();
			if (param.getId() == null) {
				int rst=as.insert(param);
				as.setEmail(param);
				//as.setPhone(param);  发送手机验证码
				return gson.toJson(rst);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "-1";
	}
	@ResponseBody
	@RequestMapping("/pass")
	private String Pass(Authentication a){
		try{
			if(as.AuthenticationPass(a))
			return "1";
			return "-1";
		}catch(Exception e){
			e.printStackTrace();
		}
		return "-1";
	}
}
